import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'
// import { getTokenTime } from '@/utils/auth'
// import router from '@/router'

// create an axios instance设置根路径
const service = axios.create(
  { baseURL: process.env.VUE_APP_BASE_API }
)
// 请求拦截器
service.interceptors.request.use(
  config => {
    // isCheckTimeOut()
    const token = store.getters.token
    if (token) {
      config.headers.Authorization = 'Bearer ' + token
    }
    return config
  }
)
// 响应拦截器
service.interceptors.response.use(
  res => {
    const { success, data, message } = res.data
    if (success) {
      return data
    } else {
      Message.error(message)
      return Promise.reject(new Error({ message: '服务器异常' }))
    }
  },
  err => {
    let text = null
    // if (err.response && err.response.data && err.response.data.code === 10002) {
    //   store.commit('user/logout')
    //   router.push('/login')
    //   text = '登录过期'
    // }
    if (err.response && err.response.status === 404) {
      text = '资源不存在'
    }
    Message.error(text || err.message)
    return Promise.reject(new Error(err))
  }
)
// function isCheckTimeOut() {
//   const currentTime = Date.now()
//   const tokenTime = getTokenTime()
//   console.log(currentTime)
//   console.log(tokenTime)
//   // return (currentTime - tokenTime) / 1000 > timeout
// }

export default service
